﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO.Packaging;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

namespace CPPEI.Coolzon.Designer.DeployTool
{
    public static class PackageUtil
    {
        /// <summary>   
        /// 递归压缩文件夹的内部方法   
        /// </summary>   
        /// <param name="folderToZip">要压缩的文件夹路径</param>   
        /// <param name="zipStream">压缩输出流</param>   
        /// <param name="parentFolderName">此文件夹的上级文件夹</param>   
        /// <returns></returns>   
        private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName, string[] sourceFiles)
        {
            bool result = true;
            ZipEntry ent = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();

            try
            {
                if (File.Exists(folderToZip))
                {
                    File.Delete(folderToZip);
                }

                foreach (string sourceFile in sourceFiles)
                {
                    string relativePath = sourceFile.Replace(folderToZip, "/");
                    relativePath = relativePath.Replace("\\", "/");
                    if (!relativePath.StartsWith("/"))
                    {
                        continue;
                    }

                    fs = File.OpenRead(sourceFile);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ent = new ZipEntry(relativePath.TrimStart('/'));
                    ent.DateTime = DateTime.Now;
                    ent.Size = fs.Length;

                    fs.Close();

                    crc.Reset();
                    crc.Update(buffer);

                    ent.Crc = crc.Value;
                    zipStream.PutNextEntry(ent);
                    zipStream.Write(buffer, 0, buffer.Length);
                }

            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }

            return result;
        }
        /// <summary>   
        /// 压缩文件夹    
        /// </summary>   
        /// <param name="folderToZip">要压缩的文件夹路径</param>   
        /// <param name="zipedFile">压缩文件完整路径</param>   
        /// <param name="password">密码</param>   
        /// <returns>是否压缩成功</returns>   
        public static bool ZipDirectory(string folderToZip, string zipedFile, string password)
        {
            bool result = false;
            if (!Directory.Exists(folderToZip))
                return result;

            ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
            zipStream.SetLevel(6);
            if (!string.IsNullOrEmpty(password)) zipStream.Password = password;


            List<string> filePaths = new List<string>();
            Stack<DirectoryInfo> dirs = new Stack<DirectoryInfo>();
            dirs.Push(new DirectoryInfo(folderToZip));
            while (dirs.Count > 0)
            {
                DirectoryInfo dir = dirs.Pop();
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    filePaths.Add(file.FullName);
                }

                DirectoryInfo[] subDirs = dir.GetDirectories();
                foreach (DirectoryInfo subDir in subDirs)
                {
                    dirs.Push(subDir);
                }
            }

            result = ZipDirectory(folderToZip, zipStream, "", filePaths.ToArray());

            zipStream.Finish();
            zipStream.Close();

            return result;
        }

        /// <summary>   
        /// 压缩文件夹   
        /// </summary>   
        /// <param name="sourceDirectory">要压缩的文件夹路径</param>   
        /// <param name="destFile">压缩文件完整路径</param>   
        /// <returns>是否压缩成功</returns>   
        public static bool Compress(string destFile, string sourceDirectory)
        {
            bool result = ZipDirectory(sourceDirectory, destFile, null);
            return result;
        }

        #region 解压  

        /// <summary>   
        /// 解压功能(解压压缩文件到指定目录)   
        /// </summary>   
        /// <param name="fileToUnZip">待解压的文件</param>   
        /// <param name="zipedFolder">指定解压目标目录</param>   
        /// <param name="password">密码</param>   
        /// <returns>解压结果</returns>   
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
        {
            bool result = true;
            FileStream fs = null;
            ZipInputStream zipStream = null;
            ZipEntry ent = null;
            string fileName;

            if (!File.Exists(fileToUnZip))
                return false;

            if (!Directory.Exists(zipedFolder))
                Directory.CreateDirectory(zipedFolder);

            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi   

                        if (fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }
                        if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                        }

                        fs = File.Create(fileName);
                        int size = 2048;
                        byte[] data = new byte[ent.Size];
                        while (true)
                        {
                            size = zipStream.Read(data, ent.Offset, (int)ent.Size);
                            if (size > 0)
                                fs.Write(data, 0, data.Length);
                            else
                                break;
                        }
                        fs.Flush();
                        fs.Close();
                    }
                }
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return result;
        }

        /// <summary>   
        /// 解压功能(解压压缩文件到指定目录)   
        /// </summary>   
        /// <param name="fileToUnZip">待解压的文件</param>   
        /// <param name="zipedFolder">指定解压目标目录</param>   
        /// <returns>解压结果</returns>   
        public static bool UnZip(string fileToUnZip, string zipedFolder)
        {
            bool result = UnZip(fileToUnZip, zipedFolder, null);
            return result;
        }
        
        public static List<string> UnZipFileNames(string fileToUnZip, string password, out string solutionText)
        {
            List<string> result = new List<string>();
            FileStream fs = null;
            ZipInputStream zipStream = null;
            ZipEntry ent = null;
            solutionText = null;

            if (!File.Exists(fileToUnZip))
                return null;

            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        string fileName = ent.Name.Replace('/', '\\');//change by Mr.HopeGi  
                        string solutionId = fileName.Split('\\')[0];
                        if(string.Equals(solutionId, Path.GetFileNameWithoutExtension(fileName)))
                        {
                            byte[] data = new byte[ent.Size];
                            zipStream.Read(data, ent.Offset, (int)ent.Size);
                            solutionText = Encoding.UTF8.GetString(data);
                        }
                        result.Add(fileName);
                    }
                }
            }
            catch
            {
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return result;
        }
        #endregion
    }
}
